package com.fenghuajueli.libbasecoreui.feedback;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.lib_pictureselect.PhotoSelectorBuilder;
import com.fenghuajueli.lib_pictureselect.config.PhotoConfig;
import com.fenghuajueli.lib_pictureselect.entity.SelectMediaEntity;
import com.fenghuajueli.lib_pictureselect.interfaces.OnSelectResultListener;
import com.fenghuajueli.libbasecoreui.BaseApplication;
import com.fenghuajueli.libbasecoreui.R;
import com.fenghuajueli.libbasecoreui.adapter.PictureAdapter;
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo;
import com.fenghuajueli.libbasecoreui.databinding.ActivityOneFeedbackWhiteBinding;
import com.fenghuajueli.libbasecoreui.databinding.ActivityThreeFeedbackWhiteBinding;
import com.fenghuajueli.libbasecoreui.dialog.CommonTipsDialog;
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils;
import com.fenghuajueli.libbasecoreui.utils.MmkvUtils;
import com.fenghuajueli.libbasecoreui.widget.CustomProgressDialog;
import com.ll.permission.AllowPermissionUseCase;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ThreeFeedbackActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String KEY_FEEDBACK_TYPE = "key_feedback_type";

    public static void start(Context context, int feedbackType) {
        Intent starter = new Intent(context, ThreeFeedbackActivity.class);
        starter.putExtra(KEY_FEEDBACK_TYPE, feedbackType);
        context.startActivity(starter);
    }

    private ActivityThreeFeedbackWhiteBinding binding;
    private Disposable dispose;
    //问题类型 使用疑问 bug反馈 会员问题
    private int feedback_type = 1;
    //上传图片的列表
    private String picPath;
    private ArrayList<String> picData = new ArrayList<>();
    private PictureAdapter adapter;
    private ArrayList<String> picUrl = new ArrayList<>();

    public static final int FEEDBACK_START = 0x01;
    public static final int FEEDBACK_SUCCESS = 0x02;
    public static final int FEEDBACK_FAILED = 0x03;
    private String feedback = "cms/feedback";

    //1默认皮肤是白色风格 2是黑色风格
    private int style = BaseApplication.getApplication().getDayNightMode();

    private String imageurlHead = "http://ss.bscstorage.com/ijj-static/";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityThreeFeedbackWhiteBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        feedback_type = getIntent().getIntExtra(KEY_FEEDBACK_TYPE, 1);
        initStatusBarColor();
        ImageTools.initBsy();
        initView();
    }

    private void initView() {
        picData.clear();
        picUrl.clear();
        if (style == 2){
            binding.onefeedbacklayout.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.top.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.middlelayout.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.bottom.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.view0.setBackgroundColor(getResources().getColor(R.color.feedbackbg_black));
            binding.imageback.setImageResource(R.mipmap.aa_icon_fh_white);
            binding.tvTitle.setTextColor(getResources().getColor(R.color.white));
            binding.tvQsType.setTextColor(getResources().getColor(R.color.white));
            binding.tvUpload.setTextColor(getResources().getColor(R.color.white));
            binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_sel_black);
            binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
            binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);

        }
        binding.tvQs1.setOnClickListener(this);
        binding.tvQs2.setOnClickListener(this);
        binding.tvQs3.setOnClickListener(this);
        binding.imageChose.setOnClickListener(this);
        binding.tvCommit.setOnClickListener(this);
        adapter = new PictureAdapter(this,picData);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        binding.picList.setLayoutManager(linearLayoutManager);
        binding.picList.setAdapter(adapter);
        adapter.setOnItemClickLitener(new PictureAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(int position) {
                picData.remove(position);
                adapter.notifyDataSetChanged();
            }
        });
        binding.imageback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_qs_1){
            changeType(1);
        }else if (id == R.id.tv_qs_2){
            changeType(2);
        }else if (id == R.id.tv_qs_3){
            changeType(3);
        }else if (id == R.id.tv_commit){

            changePicData();
        }else if (id == R.id.image_chose){
           applyPermission();
        }
    }

    /**
     * 申请权限
     */
    private void applyPermission() {
        AllowPermissionUseCase.useGalleryImages(
                this,
                "相册权限",
                "用于反馈图片上传功能，需要访问您的相册权限，如若拒绝，将无法使用上述功能。",
                "相册权限：该功能需要相册权限才可以正常运行，用于上传反馈图片。",
                "feedback",
                "请先申请相册权限!",
                () -> {
                    chose();
                    return null;
                });
    }

    //选择图片
    private void chose() {
        PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.PHOTO)
                .isCopyToPrivate(false)
                .maxCount(9)
                .minCount(1)
                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                    @Override
                    public void onResult(List<SelectMediaEntity> data) {
                       if (data == null||data.size() == 0){
                           return;
                       }
                       for (int i = 0;i < data.size();i++){
                           picPath = data.get(i).getTargetPath();
                           picData.add(picPath);
                       }
                       if (adapter != null){
                           adapter.notifyDataSetChanged();
                       }
                    }
                });
    }

    //提交反馈
    private void commit() {
        String lastFeedbackContent = MmkvUtils.get(KEY_LAST_FEEDBACK_STR, "");
        String feedbackContent = binding.etFeedbackContent.getText().toString();
        String contactWay = binding.etContactWay.getText().toString();
        if (feedbackContent.equals("")){
            ToastUtils.showShort("请先填写反馈内容~");
            return;
        } else if (feedbackContent.equals(lastFeedbackContent)) {
            ToastUtils.showShort("感谢您的反馈~");
            return;
        }
        mHandler.sendEmptyMessage(FEEDBACK_START);
        if (UserInfoUtils.getInstance().getUserInfoEntity()==null){
            mHandler.sendEmptyMessageDelayed(FEEDBACK_SUCCESS,2000);
            return;
        }
        String feedback_img = "";
        if (picUrl != null&&picUrl.size()>0){
            for (int i = 0;i < picUrl.size();i++){
                feedback_img += picUrl.get(i)+",";
            }
        }
        System.out.println("feedback_img======"+feedback_img);
        JSONObject jsonObject3 = new JSONObject();
        try {
            jsonObject3.put("feedback_type", ""+feedback_type);
            jsonObject3.put("feedback_msg",feedbackContent );
            jsonObject3.put("feedback_img", feedback_img);
            jsonObject3.put("feedback_contact", contactWay);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MmkvUtils.save(KEY_LAST_FEEDBACK_STR, feedbackContent);
        requst(AppConfigInfo.getUrl()+feedback,jsonObject3.toString(),1);
    }

    /**
     * 选择问题类型
     * @param type
     */
    public void changeType(int type){
        feedback_type = type;
        if (style == 1){
            if (type == 1){
                binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_sel);
                binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_nor);
                binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_nor);
                binding.tvQs1.setTextColor(getResources().getColor(R.color.feedback_qs_sel));
                binding.tvQs2.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
                binding.tvQs3.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
            }else if (type == 2){
                binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_sel);
                binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_nor);
                binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_nor);
                binding.tvQs2.setTextColor(getResources().getColor(R.color.feedback_qs_sel));
                binding.tvQs1.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
                binding.tvQs3.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
            }else if (type == 3){
                binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_sel);
                binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_nor);
                binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_nor);
                binding.tvQs3.setTextColor(getResources().getColor(R.color.feedback_qs_sel));
                binding.tvQs2.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
                binding.tvQs1.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
            }
        }else if (style == 2){
            if (type == 1){
                binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_sel_black);
                binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
                binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
                binding.tvQs1.setTextColor(getResources().getColor(R.color.feedback_qs_sel));
                binding.tvQs2.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
                binding.tvQs3.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
            }else if (type == 2){
                binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_sel_black);
                binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
                binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
                binding.tvQs2.setTextColor(getResources().getColor(R.color.feedback_qs_sel));
                binding.tvQs1.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
                binding.tvQs3.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
            }else if (type == 3){
                binding.tvQs3.setBackgroundResource(R.drawable.feedback_btn_question_sel_black);
                binding.tvQs2.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
                binding.tvQs1.setBackgroundResource(R.drawable.feedback_btn_question_nor_black);
                binding.tvQs3.setTextColor(getResources().getColor(R.color.feedback_qs_sel));
                binding.tvQs2.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
                binding.tvQs1.setTextColor(getResources().getColor(R.color.feedback_qs_nor));
            }
        }
    }

    public void showToast(String content) {
        ToastUtils.showShort(content);
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case FEEDBACK_START:
                    showToast("反馈中...");
                    break;

                case FEEDBACK_SUCCESS:
//                    hideLoadingDialog();
                    showToast("反馈成功！");
                    break;

                case FEEDBACK_FAILED:
//                    hideLoadingDialog();
                    showToast("反馈失败！");
                    break;
            }
        }
    };



    //发送请求的地址和数据
    public void requst(String url, String content, final int position){
        System.out.println("uurl========"+url);
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        Request request = new Request.Builder()
                .url(url)
                .addHeader("token",UserInfoUtils.getInstance().getUserInfoEntity().getToken())
                .post(RequestBody.create(mediaType, content))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("onResponse========"+e.getMessage());
                mHandler.sendEmptyMessageDelayed(FEEDBACK_FAILED,2000);

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                LogUtils.d("反馈成功==》 res = " +res);
                try {
                    JSONObject jsonObject = new JSONObject(res);
                    int code = jsonObject.getInt("code");
                    if (code == 200){
                        mHandler.sendEmptyMessageDelayed(FEEDBACK_SUCCESS,2000);
                    }else{
                        mHandler.sendEmptyMessageDelayed(FEEDBACK_FAILED,2000);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private static final String KEY_FEEDBACK_STAMP = "key_feedback_stamp";
    private static final String KEY_LAST_FEEDBACK_STR = "key_last_feedback_str";

    public void changePicData() {
        long lastStamp = MmkvUtils.get(KEY_FEEDBACK_STAMP, 0L);
        long nowStamp = System.currentTimeMillis();
        if (nowStamp - lastStamp < 1000 * 60 * 60 * 2) {
            ToastUtils.showShort("感谢您的反馈~");
            return;
        }
        MmkvUtils.save(KEY_FEEDBACK_STAMP, nowStamp);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (picData != null && picData.size() > 0) {
                    for (int i = 0; i < picData.size(); i++) {
                        picUrl.add(imageurlHead + ImageTools.getUrl(ThreeFeedbackActivity.this, picData.get(i)));
                    }
                }
                commit();
            }
        }).start();
    }

    /**
     * 初始化黑白天主题样式切换
     */
    private void initStatusBarColor() {
        if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_NO){
            //白天
            BarUtils.setStatusBarColor(this, ColorUtils.getColor(R.color.white));
            BarUtils.setStatusBarLightMode(this, true);
        } else {
            //黑天
            BarUtils.setStatusBarColor(this, ColorUtils.getColor(R.color.black));
            BarUtils.setStatusBarLightMode(this, false);
        }
    }

}
